package com.zp.business.impl.infusion;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.business.api.diagnosis.HisDiagnosis;
import com.zp.business.api.diagnosis.HisDiagnosisVo;
import com.zp.business.entity.infusion.InfusionRegisterStay;
import com.zp.business.entity.infusion.InfusionType;
import com.zp.business.entity.infusion.bo.InfusionRegisterStayBo;
import com.zp.business.entity.infusion.vo.InfusionPrescriptionVo;
import com.zp.business.entity.infusion.vo.InfusionRegisterStayVo;
import com.zp.business.entity.infusion.vo.InfusionTypeVo;
import com.zp.business.entity.patient.vo.ClinicMasterVo;
import com.zp.business.mapper.diagnosis.HisDiagnosisMapper;
import com.zp.business.mapper.infusion.InfusionRegisterStayMapper;
import com.zp.business.mapper.infusion.InfusionTypeMapper;
import com.zp.business.service.infusion.IInfusionRegisterStayService;
import com.zp.common.core.utils.DateUtils;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 输液室待登记Service业务层处理
 *
 * @author zhang peng
 * @ date 2025-02-02
 */
@RequiredArgsConstructor
@Service
public class InfusionRegisterStayServiceImpl implements IInfusionRegisterStayService {

    private final InfusionRegisterStayMapper baseMapper;
    private final InfusionTypeMapper infusionTypeMapper;
    private final HisDiagnosisMapper hisDiagnosisMapper;

    /**
     * 查询输液室待登记
     */
    @Override
    public InfusionRegisterStayVo queryById(String infusionRegisterStayId) {
        return baseMapper.selectVoById(infusionRegisterStayId);
    }

    /**
     * 查询输液室待登记列表(分页)
     */
    @Override
    public TableDataInfo<InfusionRegisterStayVo> queryPageList(InfusionRegisterStayBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<InfusionRegisterStay> lqw = buildQueryWrapper(bo);
        Page<InfusionRegisterStayVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询输液室待登记列表(不分页)
     */
    @Override
    public List<InfusionRegisterStayVo> queryList(InfusionRegisterStayBo bo) {
        LambdaQueryWrapper<InfusionRegisterStay> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<InfusionRegisterStay> buildQueryWrapper(InfusionRegisterStayBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<InfusionRegisterStay> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getClinicId()), InfusionRegisterStay::getClinicId, bo.getClinicId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), InfusionRegisterStay::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), InfusionRegisterStay::getRemarks, bo.getRemarks());
        lqw.like(StringUtils.isNotBlank(bo.getOrgName()), InfusionRegisterStay::getOrgName, bo.getOrgName());
        return lqw;
    }

    /**
     * 新增输液室待登记
     */
    @Override
    public Boolean insertByBo(InfusionRegisterStayBo bo) {
        InfusionRegisterStay add = BeanUtil.toBean(bo, InfusionRegisterStay.class);
        validEntityBeforeSave(add);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setInfusionRegisterStayId(add.getInfusionRegisterStayId());
        }
        return flag;
    }

    /**
     * 修改输液室待登记
     */
    @Override
    public Boolean updateByBo(InfusionRegisterStayBo bo) {
        InfusionRegisterStay update = BeanUtil.toBean(bo, InfusionRegisterStay.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(InfusionRegisterStay entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除输液室待登记
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询待登记的输液患者列表
     *
     * @param bo
     * @return
     */
    @Override
    public TableDataInfo<ClinicMasterVo> getInfusionRegisterStayList(InfusionRegisterStayBo bo, PageQuery pageQuery) {
        Page<ClinicMasterVo> infusionRegisterStayList = baseMapper.getInfusionRegisterStayList(pageQuery.build(), bo);
        List<String> clinicIds = new ArrayList<>();
        List<HisDiagnosisVo> hisDiagnosisVos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(infusionRegisterStayList.getRecords())) {
            clinicIds = infusionRegisterStayList.getRecords().stream().map(ClinicMasterVo::getId).collect(Collectors.toList());
            // 获取诊断信息
            hisDiagnosisVos = hisDiagnosisMapper.selectVoList(Wrappers.<HisDiagnosis>lambdaQuery()
                    .in(HisDiagnosis::getClinicId, clinicIds)
            );
        }
        List<HisDiagnosisVo> finalHisDiagnosisVos = hisDiagnosisVos;
        infusionRegisterStayList.getRecords().forEach(item -> {
            StringBuilder diagnosisStr = new StringBuilder();
            List<HisDiagnosisVo> diagnosisVoCollect = finalHisDiagnosisVos.stream()
                    .filter(e -> StringUtils.equals(e.getClinicId(), item.getId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(diagnosisVoCollect)) {
                for (HisDiagnosisVo vo : diagnosisVoCollect) {
                    diagnosisStr.append(vo.getIcdName()).append(";");
                }
            }
        });
        return TableDataInfo.build(infusionRegisterStayList);
    }

    /**
     * 查询待登记的输液患者项目明细列表
     *
     * @param bo
     * @return
     */
    @Override
    public List<InfusionPrescriptionVo> getInfusionRegisterStayItemList(InfusionRegisterStayBo bo) {
        List<InfusionTypeVo> infusionTypeVos = infusionTypeMapper.selectVoList(Wrappers.<InfusionType>lambdaQuery()
                .eq(InfusionType::getOrgId, bo.getOrgId())
                .eq(StringUtils.isNotBlank(bo.getInfusionType()), InfusionType::getInfusionType, bo.getInfusionType())
        );
        List<InfusionPrescriptionVo> prescriptionVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(infusionTypeVos)) {
            List<String> collect = infusionTypeVos.stream().map(InfusionTypeVo::getChannel).collect(Collectors.toList());
            bo.setChannelArray(collect);
            prescriptionVoList = baseMapper.getInfusionRegisterStayItemList(bo);
        }
        return initGroupNumberStyle(prescriptionVoList);
    }



    /**
     * 组织分组号 括号显示
     *
     * @param prescriptionVoList
     * @return
     */
    public List<InfusionPrescriptionVo> initGroupNumberStyle(List<InfusionPrescriptionVo> prescriptionVoList) {
        // ┍ ┕ ┌ ├ └     ╭│╰ ┆
        int groupNumber = 0;
        for (int i = 0; i < prescriptionVoList.size(); i++) {
            // 当前key值
            String currentKey = prescriptionVoList.get(i).getApplyId() + "-" + prescriptionVoList.get(i).getGroupNumber();
            // 上一条
            String previousKey = "";
            // 下一条
            String lastKey = "";
            if (i >= 1) {
                previousKey = prescriptionVoList.get(i - 1).getApplyId() + "-" + prescriptionVoList.get(i - 1).getGroupNumber();
            }
            if (i < prescriptionVoList.size() - 1) {
                lastKey = prescriptionVoList.get(i + 1).getApplyId() + "-" + prescriptionVoList.get(i + 1).getGroupNumber();
            }
            if (!StringUtils.equals(currentKey, previousKey) && !StringUtils.equals(currentKey, lastKey)) {
                groupNumber = groupNumber + 1;
                        // 当前key != 上一条key && 当前key ！= 下一条key 表示没有组号 不设置标记
                prescriptionVoList.get(i).setGroupNumberStyle("");
                prescriptionVoList.get(i).setGroupNumberShow(groupNumber);

            } else if (!StringUtils.equals(currentKey, previousKey) && StringUtils.equals(currentKey, lastKey)) {
                groupNumber = groupNumber + 1;
                // 当前key ！= 前一条key && 当前key == 下一条key 设置组号 开始 标记
                prescriptionVoList.get(i).setGroupNumberStyle("┌");
                prescriptionVoList.get(i).setGroupNumberShow(groupNumber);
            } else if (StringUtils.equals(currentKey, previousKey) && StringUtils.equals(currentKey, lastKey)) {
                // 当前key == 上一条key
                prescriptionVoList.get(i).setGroupNumberStyle("├");
                prescriptionVoList.get(i).setGroupNumberShow(groupNumber);
            } else if (StringUtils.equals(currentKey, previousKey) && !StringUtils.equals(currentKey, lastKey)) {
                // 当前key == 上一条key && 当前key ！= 下一条key 表示分组的最后一条 设置 结束 标记
                prescriptionVoList.get(i).setGroupNumberStyle("└");
                prescriptionVoList.get(i).setGroupNumberShow(groupNumber);
            }
        }
        return prescriptionVoList;
    }
}
